package com.meviewer.service;
import com.alibaba.fastjson.JSONObject;
import com.meviewer.common.JSON;
import com.meviewer.common.Registry;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import static com.meviewer.service.JsonService.readJsonFile;

 public class ViewPointService {

    String  path = Registry.getInstance().getAppStoragePath() +"BaseData/file/viewpoint.json";

    public ViewPointService(){};

    public  boolean SaveViewInfo(String contentinfo) {

        try {
            File m_viewpoint = new File(path);
            if (!m_viewpoint.exists())
            {
                m_viewpoint.createNewFile();
                Writer write = new OutputStreamWriter(new FileOutputStream(m_viewpoint), "UTF-8");
                String jsonString = "{\"viewpoistion\":[]}";
                write.write(jsonString);
                write.flush();
                write.close();
            }

            String content =  readJsonFile(path);
            JSONObject jsonObject =  JSONObject.parseObject(content);
            Object lastpoistion = jsonObject.get("viewpoistion");
            jsonObject.remove("viewpoistion");
            jsonObject.put("viewpoistion", JSONObject.parseArray(contentinfo));
            String pretty = JSON.stringify(jsonObject);
            Writer write = new OutputStreamWriter(new FileOutputStream(m_viewpoint), "UTF-8");
            write.write(pretty);
            write.flush();
            write.close();
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public String ReadViewInfo(){
        try {
            File m_viewpoint = new File(path);
            if (!m_viewpoint.exists())
            {
                String jsonString = "{\"viewpoistion\":[]}";
                return jsonString;
            }else
            {
                return readJsonFile(path);
            }

        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }
}
